﻿var savedSpan = $("#buttonthreeDays").get(0);

function cerltimespan(e,callback,autoCloseLoading) {
	if(!$(".setright").has("table [block]").is(":visible")) return;
	//if(getCookie("cerlTimespan")!=null) return;
	$('.context-menu-item').parents("table").hide();
	$(".context-menu-shadow").hide();

	$("#buttononeDay, #buttonthreeDays, #buttonweek, #buttonfifteenDays, #buttonmonth").attr("class", "timespanbutton");
	e.className = "timespanbuttonactive";

	selectedTimeSpan = $(e).attr("span");
	setCookie("_span",selectedTimeSpan,365);
	savedSpan = e;

	componentLoading($(".setright table"));
	renderAjaxCall(selectedTimeSpan,selectedDate,callback,autoCloseLoading);
}

function nowButton(){
	todayDate = getDate();
	if(selectedTimeSpan == 1) selectedDate = getDate();
	else selectedDate = getDate().addDate(-1);
	renderAjaxCall(selectedTimeSpan,selectedDate);
}

function renderAjaxCall(e,t,n,a){simpleserviceWithError("/reservationService?func=GetReservationList&span="+e+"&date="+t.toSystemFormat(),null,function(e,a){objArray=JSON.parse(e);RenderObject(objArray);if(objArray==null)CheckError();if(a==null||a)closeComponentLoading($(".setright table"));if(n!=null)n()},CheckError,null)}

function RenderObject(objArray)
{
	delete document.resList;
	document.resList = objArray;
	//setCookieMins("cerlTimespan","1",3/60)
	RenderReservationTable();
	RenderReservationObject();
	RenderCleaningStatus();
	ApplyStyleColor();
	divInTd();
	RenderDragForReservation();
	RightClick();
	RightClickCleaningMenu();
	calculateroom();
}

function RenderCleaningStatus(){
	for(var i=0;i<document.resList.Cs.length;i++)
	{
		var title=getObjectFromSharedData(SharedData.CleaningStatus,document.resList.Cs[i].s).title;
		$("[roomname="+document.resList.Cs[i].rm+"] [cleaningstatus]").attr("cleaningstatus",title);
	}
}
function ApplyStyleColor(){	
	if($("#blockedAndTask").find("style").length > 0) return;
	var style="<style>";
	for(var i=0;i<SharedData.CleaningStatus.length;i++)
		style+="[cleaningstatus='"+SharedData.CleaningStatus[i].title+"']{background-color:"+SharedData.CleaningStatus[i].color+"}";
	for(var i=0;i<SharedData.ResvStatus.length;i++)
		style+="[roomstatus='"+SharedData.ResvStatus[i].title+"']{background-color:"+SharedData.ResvStatus[i].color+"}";
	style+="</style>";
	$("#blockedAndTask").prepend(style);
}

function RenderReservationTable() 
{
	var colNum = (parseInt(selectedTimeSpan));

	//set roomType Header
	$('#blocked td[colspan]').attr('colspan',colNum + 1);

	var htmlString = "";
	var date = new Date(selectedDate.getTime());
	var date1 = getDate();

	//set date
	$("[name=spanLength]").html(date.getFormatedString() + " - " + date.addDate(colNum-1).getFormatedString());
	$("#blocked #date td:not(:first)").remove();
	for(var i=0;i<colNum;i++)
	{
		var displayColor = "#a5ddf6";
		var d = date.addDate(i);
		if(d.getTime() == getDate().getTime()) displayColor = "#4ab6ff";
		$("#blocked #date").append("<td style=\"border:1px ridge #fff; background-color:" + displayColor + ";width:" + (84/colNum) + "%\" date=\"" + d.toSystemFormat() + "\">" + d.toFormatString('dd') + "<br/>"+ShortDay[d.getDay()]+"</td>");
	}
	if($("#clonedateforscroll").size()>0){
		$("#clonedateforscroll tr").replaceWith($("#blocked #date").clone());
		$("#clonedateforscroll tr").find("td").each(function(n){$(this).width($($(".setright table tr:first td").get(n)).width());})
	}
	
	//set total
	var totals = $(".totalcheckinroom").add("[totaltype]");
	$(".totalcheckinroom").find("td:not(.cell1)").remove();
	date = new Date(selectedDate.getTime());
	for(var i=0;i<colNum;i++){
		$(".totalcheckinroom").append("<td class=\"cell\" date=\""+date.toSystemFormat()+"\"></td>");
		date.setDate(date.getDate()+1);
	}
	
	//set each room
	var rooms = $('#blocked tr[roomName]');
	for(var j=0;j<rooms.size();j++)
	{
		var first = $(rooms[j]).find("td:first");
		htmlString = first.clone().wrap('<div/>').parent().html();
		date = new Date(selectedDate.getTime());

		var  divString = "<div></div>"
		for(i=0;i<colNum;i++)
		{
			var date1 = date.toSystemFormat().split("-");
			var dateMsec = new Date(date1[0],date1[1]-1,date1[2]).getTime();
			var dateNow = getDate().toSystemFormat().split("-");
			var datNowMsec = new Date(dateNow[0],dateNow[1]-1,dateNow[2]).getTime();
			if(dateMsec >= datNowMsec){
				htmlString += "<td class=\"cell\" date=\"" + date.toSystemFormat() + "\" ></td>";
			}else{
				htmlString += "<td class=\"cell deactive\" date=\"" + date.toSystemFormat() + "\"></td>";
			}
			date.setDate(date.getDate()+1);
		}
		$(rooms[j]).html(htmlString);
	}
}

function RenderReservationObject()
{
	var objArray = document.resList.ResLst;
	for(i=0;i<objArray.length;i++)
	{
		var roomName = objArray[i].rmId;
		var date = new Date(objArray[i].d).toSystemFormat();
		var cell = $("[roomname='" + roomName + "'] [date='"+date+"']");
		if(cell.size() == 0)
		{
			var selectEls = $("div[order]").parent();
			var compDate = new Date(objArray[i].d);
			for(var j=0;j<selectEls.size();j++)
			{
				var thisDate = $.datepicker.parseDate("yy-mm-dd",$(selectEls[j]).attr("date"));
				var span = $(selectEls[j]).attr("colspan");
				if(span == null) span = "1";
				var to = thisDate.addDate(parseInt(span));
				if($(selectEls[j]).attr("roomname") == roomName &&
					compDate >= thisDate && compDate < to)
					{
						cell = $(selectEls[j]);
						break;
					}
			}
		}
		var reservationItem = CreateReservationElement(objArray[i]);
		
		//span > 1
		if(objArray[i].s > 1)
		{
			var d = new Date(objArray[i].d);
			
			for(s=1;s<objArray[i].s;s++)
			{
				d.setDate(d.getDate()+1);
				var dateString = d.toSystemFormat();
				cell.parent().find("td[date='" + dateString + "']").remove();
			}
			cell.parent().find("td[date='" + new Date(objArray[i].d).toSystemFormat() + "']").attr("colspan",objArray[i].s);
			var tmpDate = new Date(objArray[i].rlD);
			if(tmpDate < getDate() && tmpDate.addDate(objArray[i].rlS) >= getDate())
				cell.removeClass("deactive");
		}
			
		if(cell.find("div").size() > 0) cell.html(cell.html() + reservationItem);
		else cell.html(reservationItem);
		
		//sort item
		if(cell.find("div").size() > 1 && cell.find("div").attr("order") != null)
		{
			var listitems = cell.children('div').get();
			listitems.sort(function(a, b) {
				var compA = new Date(a.getAttribute("date"));
				var compB = new Date(b.getAttribute("date"));
				var compC = parseInt(a.getAttribute("order"));
				var compD = parseInt(b.getAttribute("order"));
				if(compA < compB) return 0;
				else if(compA > compB) return 1;
				else return (compC < compD)? 0:1;
			});
			cell.html(listitems);
		}
		//remove line at first reservation
		cell.find("div:first").css("background-image","");
	}
	CreateSellRoom();
}

function getObjFromCell(cell){
	var id = $(cell).attr("res");
	var sub = $(cell).attr("subid");
	if(sub==null) sub=0;
	for(var j=0;j<document.resList.ResLst.length;j++)
		if(document.resList.ResLst[j].id == id && document.resList.ResLst[j].subId == sub)
			return document.resList.ResLst[j];
	return null;
}

function renderDNRItem(objArrayItem){
	var resStatus = getObjectFromSharedData(SharedData.ResvStatus,objArrayItem.rsSt);
	var name = "DNR";
	var elementFormat = '<div order="1" dnr="{0}" onClick="DNRonclick(this)" title="{1}" style="">&nbsp;&nbsp;{2}</div>';
	var newElement = $(elementFormat.format(objArrayItem.id,name,name));
	newElement.css("width","100%");
	newElement.css("background",resStatus.color + " url(images/line.jpg) repeat-y");
	return newElement;
}

function DNRonclick(el){
	window.currentDNRElement = el;
	$.getScriptIfNotExist('/js/components/timespan/DNR.js',function(script,textStatus,e){
		var el = window.currentDNRElement;
		delete window.currentDNRElement;
		showDNRDialog($(el));
	})
}

function CreateReservationElement(objArrayItem)
{
	var resStatus = getObjectFromSharedData(SharedData.ResvStatus,objArrayItem.rsSt);
	if(resStatus.title == "DNR") return renderDNRItem(objArrayItem);
	var name = (objArrayItem.gId != 0 && objArrayItem.gId != null)? objArrayItem.gNm + "(G)":objArrayItem.nm;
	if(name == null) name=""; 

	if(objArrayItem.A) name += "(A)";
	var subId = (objArrayItem.subId != 0)? ' subId="'+objArrayItem.subId+'"' : "";
	var order = ' order="' + objArrayItem.o + '"';
	var res = ' res="'+ objArrayItem.id +'"';
	var roomstatus = ' roomstatus="'+resStatus.title+'"';
	var title = objArrayItem.id + " " + name;
	
	var attrs = order + res + subId + roomstatus;
	
	var elementFormat = '<div {0} onClick=\"showBooking(this)\" title="{1}">&nbsp;&nbsp;{2}</div>';

	if(objArrayItem.ct && objArrayItem.cf)
		element = elementFormat.format(attrs,title,
			'<div class="arrow-left"></div>' 
			 + '<div class="arrow-right"></div>'
			 + name);
	else if(objArrayItem.cf)
		element = elementFormat.format(attrs,title,'<div class="arrow-left"></div>' + name);
	else if(objArrayItem.ct)
		element = elementFormat.format(attrs,title,'<div class="arrow-right"></div>' + name);
	if(objArrayItem.ct != true && objArrayItem.cf != true)
		element = elementFormat.format(attrs,title, name);
	var newElement = $(element);
	
	newElement.css("width","100%");
	//newElement.css("background-image","url(images/line.jpg)");
	//newElement.css("background-repeat","repeat-y");
	return newElement.clone().wrap('<div/>').parent().html();
}

function divInTd(){
	var domD = $("td.cell[date]");
	for(var i = 0;i<domD.length;i++)
		if(domD[i].innerHTML == "")
			if($.datepicker.parseDate("yy-mm-dd",domD[i].getAttribute("date")) >= getDate())
				domD[i].innerHTML = "<div onclick=\"BookingG(this)\"></div>";
}
function CheckError(e,a){ if(a==null||a)closeComponentLoading($(".setright table"));simpleDialog(Message_loadFail); }

function RightClick()
{ 
	var ArraySuite = $(".vmenu .first_li");
	var list = [];
	
	function findObject(name)
	{
		for(var i=0;i<list.length;i++)
			if(list[i].name == name)
				return list[i];
		return null;
	}
	
	for (var m=0; m<ArraySuite.length; m++) 
	{
		var obj = {};
		obj.name = ArraySuite[m].getAttribute("name");
		obj.title = $.trim(ArraySuite[m].innerText);
		list.push(obj);
	}
	
	findObject("cancelCheckIn").func = function(menuItem,menuObject) { editAfterRes(this,"CancelCheckin"),calculateroom()};
	
	findObject("checkIn").func = function(menuItem,menuObject) { $(this).attr({'roomstatus':'Checked-in Rooms'}),editAfterRes(this),calculateroom()};
	
	findObject("checkOut").func = function(menuItem,menuObject) { $(this).attr({'roomstatus':'Checked-out Rooms'}),editAfterRes(this),calculateroom()};
	
	findObject("cancelCheckOut").func = function(menuItem,menuObject) {
		/*var roomStatus_editAfRes =$(this).attr("roomstatus");
		var resIdDiv = $(this).attr("res");
		var chenckEmptyRoom =$("[res=\""+resIdDiv+"\"]").parents("td:first").children('div:last').attr("roomstatus"); 
		
		if(chenckEmptyRoom == null && roomStatus_editAfRes == "Checked-in Rooms"){
			$(this).removeAttr("issellroom")
			$("[res=\""+resIdDiv+"\"]").parent().children('div').last().remove()
			$("[res=\""+resIdDiv+"\"]").parent().find("div").css("width","100%")
		}*/
		editAfterRes(this,"CancelCheckout");
		calculateroom();
	};
	
	findObject("assignRoom").func = function(menuItem,menuObject) { getObjFromCell(this).A = true,
		editAfterRes(this)
		if(getObjFromCell(this).A)
			simpleDialog("Change room to isassign successful.");
		else
			simpleDialog("Can't change room to isassign please check again. !! ");
	};
	
	findObject("noneAssignRoom").func = function(menuItem,menuObject) { getObjFromCell(this).A = false,
		editAfterRes(this)
		if(!getObjFromCell(this).A)
			simpleDialog("Change room to unassign successful.");
		else
			simpleDialog("Can't Change room to unassign please check again. !! ");
	};
	
	findObject("payment").func = function(menuItem,menuObject) {
		if($("div[forload=editreserved] #payment-dialog").size() == 0){
			document.rightclickAtElemnt = this;
			waitingDialog({});
			var div = $("<div>");
			$("div[forload=editreserved]").append(div);
			div.load("/components/Payment/Payment.jsp",function(){
				var el = document.rightclickAtElemnt;
				delete document.rightclickAtElemnt;
				OpenPaymentPageforRight(el)
			});
		}
		else{
			OpenPaymentPageforRight(this)
		}
	};
	
	findObject("extendSplit").func = function(menuItem,menuObject) { IncreaseResDay(this)};
	
	findObject("Detailed").func = function(menuItem,menuObject) {
		if($("div[forload=editreserved] [name=editReserved_group]").size() == 0){
			document.rightclickAtElemnt = this;
			var div = $("<div>");
			$("div[forload=editreserved]").append(div);
			waitingDialog();
			div.load("components/EditReserved/EditReserved.jsp",function(){
				var el = document.rightclickAtElemnt;
				delete document.rightclickAtElemnt;
				OpenDateilPage(el);
			});
		}
		else{
			OpenDateilPage(this);
		}
	};
	
	findObject("groupCheckIn").func = function(menuItem,menuObject) {btnCheckInGroupforRightClick(this)};
	findObject("grupCheckOut").func = function(menuItem,menuObject) {btnCheckOutGroupforRightClick(this)};
	findObject("splitRoom").func = function(menuItem,menuObject) {splitReservationToday(this);};
	findObject("move").func = function(menuItem,menuObject) {enableDragReservation(this); };
	findObject("addTask").func = function(menuItem,menuObject) { alert('coming soon')};
	findObject("sellRoom").func = function(menuItem,menuObject) { 
		var resIdDiv = $(this).attr("res");
		var colspan = $(this).parents("td:first").attr("colspan");
		if(colspan==null) colspan=1;
		
		var widthDiv = 100-(100-(100/parseInt(colspan))+((100/parseInt(colspan )))/2);
		var pW = $(this).parents("td:first").width();
		if(parseInt(colspan)>=2){
			var drawSpan =$(this).parents("td:first").find("div").css("width",(100-(100/parseInt(colspan))+((100/parseInt(colspan )))/2) + "%");
		}
		else{
			var drawSpan =$(this).parents("td:first").find("div").css("width",(100/2) + "%");
		}

		var cW =$("[res=\""+resIdDiv+"\"]").width();
		var obj = getObjFromCell(this);
		var newDate = $.datepicker.parseDate("yy-mm-dd",$("[res=\""+resIdDiv+"\"]").parents("td:first").attr("date")).addDate(obj.s - 1).toSystemFormat();
		
		$("[res=\""+resIdDiv+"\"]").after("<div name=\"emptyDiv\" style=\"width:"+(pW-cW)+"px; float:left;\" onclick=\"BookingG(this)\"></div>")
		
		calculateroom(),editAfterRes(this)
	};

	findObject("cancelReservation").func = function(menuItem,menuObject) {
		editAfterRes(this,"CancelRes"),calculateroom()};
		$('.cell div[res]').contextMenu(list,{
		beforeShow: function() { 
			$(this.menu).find('.context-menu-item-disabled').attr('Class','context-menu-item');
			var dateNow = getDate();
			var obj = getObjFromCell($($(this).get(0).target));
			var resElement = obj.id;
			var isAssElement = obj.A;
			var isGroupElement = obj.gId;
			var checkDateNow = new Date(obj.rlD).toSystemFormat();
			var isSellroom = obj.sRm;
			var realResDate = new Date(obj.rlD);
			var roomForcheck = getObjectFromSharedData(SharedData.ResvStatus,obj.rsSt).title;
			if(roomForcheck=="Reserved Rooms"||roomForcheck=="Temp Rooms"){
				if(isAssElement)
				{	
					if(isGroupElement == 0){
						$('.context-menu-item[name=groupCheckIn]').attr("class","context-menu-item context-menu-item-disabled");	
					}
						$('.context-menu-item[name=assignRoom],.context-menu-item[name=grupCheckOut],'+
						'.context-menu-item[name=sellRoom]').addClass("context-menu-item context-menu-item-disabled");
				} if(!isAssElement)
				{
					if(isGroupElement == 0){
						$('.context-menu-item[name=groupCheckIn]').addClass("context-menu-item context-menu-item-disabled");
					}
						$('.context-menu-item[name=noneAssignRoom],.context-menu-item[name=grupCheckOut],'+
						'.context-menu-item[name=sellRoom]').addClass("context-menu-item context-menu-item-disabled");
				}
				 if(realResDate > dateNow)
				 {
					 $('.context-menu-item[name=groupCheckIn],.context-menu-item[name=checkIn]').addClass("context-menu-item context-menu-item-disabled");
				 }
				 $('.context-menu-item[name=cancelCheckIn],.context-menu-item[name=checkOut],'+
				 '.context-menu-item[name=cancelCheckOut]').addClass("context-menu-item context-menu-item-disabled");
			}
			else if(roomForcheck=="Checked-in Rooms" ){
					$('.context-menu-item[name=checkIn],.context-menu-item[name=cancelCheckOut]').addClass("context-menu-item context-menu-item-disabled");
					(isAssElement)?$('.context-menu-item[name=assignRoom]').addClass("context-menu-item context-menu-item-disabled"):
					$('.context-menu-item[name=noneAssignRoom],'+
					'.context-menu-item[name=splitRoom],.context-menu-item[name=extendSplit]').addClass("context-menu-item context-menu-item-disabled");
					
					$('.context-menu-item[name=groupCheckIn],'+
					'.context-menu-item[name=sellRoom],.context-menu-item[name=cancelReservation]').addClass("context-menu-item context-menu-item-disabled");
					if(realResDate == dateNow)
					{
						if(isGroupElement == 0)
						{
							$('.context-menu-item[name=grupCheckOut]').addClass("context-menu-item context-menu-item-disabled");
						}
					}else
					{
						if(isGroupElement == 0)
						{
							$('.context-menu-item[name=grupCheckOut],.context-menu-item[name=addTask]').addClass("context-menu-item context-menu-item-disabled");
						}
				}	
			}
			else if(roomForcheck=="Checked-out Rooms"){
				var getRoomName = $("[res=\""+resElement+"\"]").parents("[roomname]:first").attr("roomname");
				var checkRoomStatus =$("[res=\""+resElement+"\"]").parents("tr").find("[cleaningstatus]").attr("cleaningstatus");
				
					$('.context-menu-item[name=cancelCheckIn],.context-menu-item[name=checkIn],.context-menu-item[name=checkOut],'+
					'.context-menu-item[name=assignRoom],.context-menu-item[name=noneAssignRoom],.context-menu-item[name=extendSplit],'+
					'.context-menu-item[name=groupCheckIn],.context-menu-item[name=grupCheckOut],.context-menu-item[name=splitRoom],'+
					'.context-menu-item[name=cancelReservation],.context-menu-item[name=move]').addClass("context-menu-item context-menu-item-disabled");
					($.datepicker.parseDate("yy-mm-dd",checkDateNow).addDate(obj.rlS-1).toSystemFormat() != dateNow.toSystemFormat()||isSellroom)?$('.context-menu-item[name=sellRoom]').addClass("context-menu-item context-menu-item-disabled"):"";
				
			}
			else if(checkRoomStatus !="Clean Rooms" || chenckEmptyRoom == null)
			{
				$('.context-menu-item[name=cancelCheckIn],.context-menu-item[name=checkIn],.context-menu-item[name=checkOut],'+
				'.context-menu-item[name=assignRoom],.context-menu-item[name=noneAssignRoom],.context-menu-item[name=extendSplit],'+
				'.context-menu-item[name=groupCheckIn],.context-menu-item[name=grupCheckOut],.context-menu-item[name=splitRoom],'+
				'.context-menu-item[name=sellRoom],.context-menu-item[name=cancelReservation]').addClass("context-menu-item context-menu-item-disabled");
			}
		}
	});
}

function IncreaseResDay(el){
	var id = $(el).attr("res");
	componentLoading($("#blocked"));
	simpleserviceWithError("/reservationService",{func:"IncreaseReservation",resId:id,days:1},function(data){
		closeComponentLoading($("#blocked"));
		var objArray = JSON.parse(data);
		if(objArray.PackageTable == null)
			splitReservationExtend(el);
		else{
			ResetSplitTable(objArray.SplitTable);
			ResetChargeList(objArray.ChargeList);
			ResetPackageTable(objArray.PackageTable);
			cerltimespan(savedSpan);
		}
	},function(){
		closeComponentLoading($("#blocked"));
	});
	//closeComponentLoading
}

function RightClickCleaningMenu()
{

	var menuArray = []; 
	var ArraySuite;
	
	ArraySuite = $(".vmenu_cleaningMenu .first_li span");
	for (var m=0; m<ArraySuite.length; m++) 
	{
		var o; 
		o=ArraySuite[m].innerHTML;
		menuArray.push(o); 
	}
	var rightclick_cleaningMenu_menulist=[];
	var cleaningMenu = {};
	cleaningMenu[menuArray[0]]=function(menuItem,menuObject) { $(this).css({'backgroundColor':'#B79FE7'})
		,$(this).attr({'cleaningstatus':'Touch-Up Rooms'}),editCleaningStatus(this)};
		cleaningMenu[menuArray[1]]=function(menuItem,menuObject) { $(this).css({'backgroundColor':'#D6BCBC'})
		,$(this).attr({'cleaningstatus':'Dirty Rooms'}),editCleaningStatus(this)};
		cleaningMenu[menuArray[2]]=function(menuItem,menuObject) { $(this).css({'backgroundColor':'#E79F9F'})
		,$(this).attr({'cleaningstatus':'Inspect Rooms'}),editCleaningStatus(this)};
		cleaningMenu[menuArray[3]]=function(menuItem,menuObject) {  $(this).css({'backgroundColor':'#FFFFFF'})
		,$(this).attr({'cleaningstatus':'Clean Rooms'}),editCleaningStatus(this)};
		cleaningMenu[menuArray[4]]=function(menuItem,menuObject) {$(this).css({'backgroundColor':'#C7C7AD'})
		,$(this).attr({'cleaningstatus':'Repair Rooms'}),editCleaningStatus(this)};
		cleaningMenu[menuArray[5]]=function(menuItem,menuObject) {$(this).css({/*'backgroundColor':'#D6AE00'*/})
		,$(this).attr({'cleaningstatus':'DNR'}),
			window.addDNR = $(this);
			$.getScriptIfNotExist("/js/components/timespan/DNR.js",function(script,textStatus,e){
				var dom = window.addDNR;
				delete window.addDNR;
				PopupDNR(dom.parents("[roomname]").attr("roomname"),$.trim(dom.html()));
			})
		};
		rightclick_cleaningMenu_menulist.push(cleaningMenu);

	$(".cell[cleaningstatus]").contextMenu(rightclick_cleaningMenu_menulist,{
		beforeShow: function() { 
			var _attr = $(this).get(0).target.getAttribute("cleaningstatus");
			var roomname = $(this).get(0).target.getAttribute("roomname");
			if(_attr == "DNR") return;
			//$(this).get(0).target.setAttribute('Class','context-menu-item');
			var _size=$('.context-menu-item').parents("table").size();
			$('.context-menu-item').parents("table").hide().get(_size-1);
			$(".context-menu-shadow").hide().get(_size-1);

			$(this.menu).find('.context-menu-item-disabled').attr('Class','context-menu-item');
			$(this.menu).find('.context-menu-item').parent().css("width","120px");
			$(this.menu).find('.context-menu-item').parent().css("height","80px");

			var _i = 0;
			if(_attr=="Touch-Up Rooms") _i = 0;
			else if(_attr=="Dirty Rooms") _i = 1;
			else if(_attr=="Inspect Rooms") _i = 2;
			else if(_attr=="Clean Rooms") _i = 3;
			else if(_attr=="Repair Rooms") _i = 4;
			this.menu.find('.context-menu-item')[_i].setAttribute("Class","context-menu-item context-menu-item-disabled");	
		}
	});
}
function calculateroom()
{
	var roomList = $("#blocked tr[roomname]");
	var totalList = $(".totalcheckinroom");
	CalcTotalRoomCount(roomList,totalList);
	
	if($(".totalRoomtypeBlock[name=checkIn]").size()>0){
		$(".totalRoomtypeBlock[name=checkIn]").each(function(){
			if($(this).attr("roomtype")!=null)
				displayCountRoomType($("[roomtype="+$(this).attr("roomtype")+"]:not([roomname]):not(.totalRoomtypeBlock)")[0],true);
			else
				displayCountBlock($("[block="+$(this).attr("block")+"]:not([roomtype]):not(.totalRoomtypeBlock)")[0],true);
		});
	}
}

function CalcTotalRoomCount(roomList,totalList)
{
	totalList.filter("[name=roomAmount]").find("td:not(.cell1)").html(roomList.size());
	totalList.filter("[name=unoccupied]").find("td:not(.cell1)").html(roomList.size());
	totalList.filter("[name=checkIn]").find("td:not(.cell1)").html(0);
	totalList.filter("[name=book]").find("td:not(.cell1)").html(0);
	totalList.filter("[name=totalSell]").find("td:not(.cell1)").html(0);
	
	//calc all resv
	var resList = roomList.find("div[res]");
	for(var i=0;i<resList.length;i++){
		var obj = getObjFromCell($(resList[i]));
		var status = getObjectFromSharedData(SharedData.ResvStatus,obj.rsSt).title;
		var date = new Date(obj.d);
		var span = obj.s;
		for(var j=0;j<span;j++)
		{
			var specificDate = "[date="+date.addDate(j).toSystemFormat()+"]";
			if(status=="Reserved Rooms"){
				increaseItem(totalList.filter("[name=book]").find(specificDate));
				increaseItem(totalList.filter("[name=totalSell]").find(specificDate));
				decreaseItem(totalList.filter("[name=unoccupied]").find(specificDate));
			}
			else if(status == "Checked-in Rooms")
			{
				increaseItem(totalList.filter("[name=checkIn]").find(specificDate));
				increaseItem(totalList.filter("[name=totalSell]").find(specificDate));
				decreaseItem(totalList.filter("[name=unoccupied]").find(specificDate));
			}
			else if(status == "Checked-out Rooms")
			{
				//check last date can be split
				if(j+1 == span)
				{
					var last = $(resList[i]).parents("td:first").children("div:last");
					if(last.attr("name") == null || last.attr("name") != "emptyDiv")
						decreaseItem(totalList.filter("[name=unoccupied]").find(specificDate));
				}
				else
					decreaseItem(totalList.filter("[name=unoccupied]").find(specificDate));
			}
			else if(status == "Temp Rooms")
				decreaseItem(totalList.filter("[name=unoccupied]").find(specificDate));
		}
	}
}

function increaseItem(dom){dom.html(parseInt(dom.html())+1);}
function decreaseItem(dom){dom.html(parseInt(dom.html())-1);}

function editAfterRes(e,cType) {
	var roomStatus_editAfRes=$(e).attr("roomstatus");
	var resId_editAfRes =$(e).attr("res");
	var obj = getObjFromCell(e);
	var isAss_editAfRes=obj.A;
	var chenckEmptyRoom=$(e).parents("td:first").children("div:last").attr("roomstatus"); 
	var sellRoom_editAfRes = false;
	if(chenckEmptyRoom == null && roomStatus_editAfRes == "Checked-out Rooms")
		var sellRoom_editAfRes = true;
	var nowDate = getServerDateTime().toFormatString("yyyy-MM-dd hh:mm");
	var sellRooms = false;
	var Type ="Single";
	if(cType !=null){
		var status="";
		(cType=="CancelCheckout")?status ="Checked-in Rooms":status="Reserved Rooms";
		(cType=="CancelRes")?status ="Cancel Reservation":"";
		CreateChargeforRightclick(status,sellRooms,cType,isAss_editAfRes,Type,resId_editAfRes);
	}else{
		var link = "/reservationService?func=editAfterRes&resId=" +resId_editAfRes+"&reservationstatus="+roomStatus_editAfRes+"&sellroom="+sellRoom_editAfRes+"&isassign="+isAss_editAfRes+"&dateCheckin="+nowDate;
		simpleserviceWithError(link,null,function(data){
			objArray = JSON.parse(data);
			setTimeout(function(){showNumberall_reservation();},50);
			cerltimespan($(".timespanbuttonactive").get(0));
			if(objArray == null) CheckError();
		},CheckError,null);
	}
}

function RemoveReservedRoom(resIdDiv) {
	var link = "/reservationService?func=removeRes&resId=" +resIdDiv;
	simpleserviceWithError(link,null,function(data){
		objArray = JSON.parse(data);
		cerltimespan($(".timespanbuttonactive").get(0));
		if(objArray == null) CheckError();
	},CheckError,null);
}

function editCleaningStatus(e) {
	var status = getObjectFromDataIndex(SharedData.CleaningStatus,"title",e.getAttribute("cleaningstatus"));
	var link = "/roomService?func=changCleaningStatus&roomId=" +$(e).parents("[roomname]").attr("roomname")+"&cleanStatus="+status.id;
	simpleserviceWithError(link,null,function(data){
		objArray = JSON.parse(data);
		if(objArray == null) CheckError();
	},CheckError,null);
}

function CreateSellRoom()
{
	$("[roomstatus=\"Checked-out Rooms\"]").parent().each(function(e){
		var last = $(this).find(":last[order]");
		var lastobj = getObjFromCell(last);
		var thisObj = getObjFromCell(this)
		if(lastobj.sRm){
			var spanTo = new Date(lastobj.rlD).addDate(lastobj.rlS-1).toSystemFormat();
			var span = $(this).attr("colspan");
			if(span == null) span="1";
			var newDate = $.datepicker.parseDate("yy-mm-dd",$(this).attr("date")).addDate(span - 1).toSystemFormat();
			if(spanTo == newDate && $.datepicker.parseDate("yy-mm-dd",newDate) >= getDate())
			{
				var order = parseInt($(this).find(":last[order]").attr("order")) + 1;
				$(this).find(":last").after("<div name=\"emptyDiv\" order=\""+order+"\" style=\"width:50%;\" onclick=\"BookingG(this)\"></div>");
			}
		}
	});
	//change res size
	var p = $(".cell div:nth-child(2)").parent();
	for(var i=0; i< p.length;i++)
	{
		var cell = $(p.get(i));
		var spanDate = cell.attr("colspan");
		if(spanDate == null) { spanDate = 1; }
		var pcPerDay = (100.0 / spanDate);
		cell.find("[order]").each( function() {
			var obj = getObjFromCell(this);
			var span = (obj==null && $(this).attr("name")=="emptyDiv")? 1 : obj.s;
			var date = (obj==null && $(this).attr("name")=="emptyDiv")? $(this).parent("td:first").attr("date") : obj.d;
			var spanTo = new Date(date).addDate(parseInt(span) - 1).toSystemFormat();
			var dim = $(this).parent().find("[order]").size() + 1;
			if($(this).parent().attr("colspan") == null) dim = dim -1;
			var percent = (span * pcPerDay) - ((pcPerDay / dim) * (dim -1));
			$(this).css("width",percent+"%");
		});
	}
}

function CreateChargeforRightclick(status,sellRooms,cType,isAssign,roomType,ResId)
{
	var content = $('<table class="simpleTable" name="for_charge_dialog"><tr>' +
			'<td style="width:80px;">'+Popup_label_Cancel_Reason+' : </td>' +
			'<td><div style="display:table-cell;"><span class="margin-right"><select id="insert-reason-reason"></select></span>' +
			'Charge : <input type="text" class="currency" id="insert-reason-cost"> <span name="unit-money"> '+SharedData.General.defaultCurrency.symbol+'</span></div></td>' +
		'</tr>'+
		'<tr><td>&nbsp;</td><td><span name="displayTime" class="link">'+Popup_label_insert_time+'</span></td></tr>' +
		'<tr name="time" style="display:none;"><td>&nbsp;</td><td>' +
			'<select></select> : <select></select>'+Popup_label_time+
		'</td></tr>' +
		'<tr><td>'+Popup_label_Cancel_detail+' : </td>' +
			'<td><textarea id="insert-cancel-resondetail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'<tr><td></td><td>' +
			'<div style="display:table-cell; float:left;"><input type="checkbox" name="insert-reason-send-email" /> '+Popup_label_Cancel_SendEmail + '</div>' +
			'<div name="btnEditMail" class="link" style="float:right; display:table-cell; display:none; margin-top:4px;">'+Popup_label_Cancel_insert_mail+'</div>' +
		'</td></tr>' +
		'<tr name="insert-mail" style="display:none;"><td>&nbsp;</td>' +
			'<td><textarea id="insert-cancel-mail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'</table>');

	//fill Reason
	for(var i=0;i<SharedData.CancelReason.length;i++)
		content.find("#insert-reason-reason").append(optionString.format(SharedData.CancelReason[i].id,SharedData.CancelReason[i].Description));
	for(var i=0;i<24;i++)
		content.find("[name='time'] select:first").append(optionString.format(i,i));
	for(var i=0;i<60;i+=5)
		content.find("[name='time'] select:nth-child(2)").append(optionString.format(i,i));
	content.find("#insert-reason-cost").val((0).toFixed(SharedData.General.currencyDecimalPlaces));
	content.find("#insert-reason-cost").attr("placeholder",(0).toFixed(SharedData.General.currencyDecimalPlaces));
	var buttons = [
		{ title:Popup_btn_Cancel_resv , callback: function(thisdialog,args){
			var h = ($("[name=time]:visible").find("td:Last select:first").val()!=null)?$("[name=time]:visible").find("td:Last select:first").val():getServerDateTime().getHours().toString();
			var m = ($("[name=time]:visible").find("td:Last select:Last").val()!=null)?$("[name=time]:visible").find("td:Last select:Last").val():getServerDateTime().getMinutes().toString();
			var cost = ($("#insert-reason-cost").val()=="")?0:$("#insert-reason-cost").val();
			var data={
				func:"addCharge",
				resId:ResId,
				reason:$('#insert-reason-reason').find(':selected').text(),
				description:$("#insert-cancel-resondetail").val(),
				chargeQty:"0",
				discount:"0",
				subFolio:null,
				tax:0,
				isLock:false,
				isRoomCharge:false,
				type:roomType,
				chargeAmount:cost,
				chargeDate:getServerDateTime().toSystemFormat()+" "+h+":"+m,
				emailMassage:$("#insert-cancel-mail").val(),
				resStatus:status,
				sellRoom:sellRooms,
				isAssign:isAssign,
				chargeType:cType,
				groupId:0,
				span:0,
				rmId:null,
				rmType:null,
				priceRate:null,
				adult:1,
				child:0,
				guest:0,
				sal:0,
				nm:"",
				lsNm:"",
				phone:"",
				mail:"",
				roomamount:0,
				agency:"",
				agencyId:"0",
				pay:0
			};
			simpleserviceWithArgs("/chargeService",data,btnClickSuccess,null);
			thisdialog.dialog("close");
		}},
		{ title:simpleLabel_Button_Close , callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}}
	];
	var msgDialog = customDialog(Popup_ReasonCancellation_title,content.wrap('<div/>').parent().html(),{ width: 600},buttons,null);
	msgDialog.find("[name='displayTime']").click(function(){ msgDialog.find("[name='time']").css("display",""); });
	msgDialog.find("[name='btnEditMail']").click(function(){ msgDialog.find("[name='insert-mail']").css("display",""); });
	msgDialog.find("[name='insert-reason-send-email']").change(function(){
		if(this.checked)
			msgDialog.find("[name='btnEditMail']").css("display","");
		else{
			msgDialog.find("[name='btnEditMail']").css("display","none");
			msgDialog.find("[name='insert-mail']").css("display","none");
		}
	});
}

function  btnCheckInGroupforRightClick(e) {
	var o = getObjFromCell(e);
	var groupId = o.gId;
	
	var obj ={};
	obj.resList=[];
	for(var i=0;i<document.resList.ResLst.length;i++)
		if(document.resList.ResLst[i].gId == groupId)
			obj.resList.push(document.resList.ResLst[i].id);
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = true;
	obj.roomStatus_editAfRes = "Checked-in Rooms";
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;
	
	waitingDialog();
	var link ="/reservationService?func=editAfterRes&resId=" +obj.resList+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
	simpleserviceWithArgs(link,null,btnClickSuccess,null);
}

function  btnCheckOutGroupforRightClick(e) {
	var o = getObjFromCell(e);
	var groupId = o.gId;
	
	var obj ={};
	obj.resList=[];
	for(var i=0;i<document.resList.ResLst.length;i++)
		if(document.resList.ResLst[i].gId == groupId)
			obj.resList.push(document.resList.ResLst[i].id);
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = true;
	obj.roomStatus_editAfRes = "Checked-out Rooms";
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;
	
	var link ="/reservationService?func=editAfterRes&resId=" +obj.resList+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
	simpleserviceWithArgs(link,null,btnClickSuccess,null);
}

function OpenDateilPage(e)
{
	var groupId = getObjFromCell(e).gId;
	var Type="btnEditS";
	var resId =$(e).attr("res");
	if(groupId!=0){Type="btnEditG"; resId =groupId;}
	CallEditReseredPage(Type,resId);
}
function OpenPaymentPageforRight(e)
{
	var obj = getObjFromCell(e);
	var Type=(obj.gId==0)? "pamentPageS":"pamentPageG";
	var resId =(obj.gId==0)? obj.id:obj.gId;
	OpenPaymentPageforRightByResId(resId,Type);
}
function OpenPaymentPageforRightByResId(resId,Type){
	var ScritpArray=[];
	ScritpArray.push("/js/components/Payment/Charges.js");
	ScritpArray.push("/js/components/Payment/Refund.js");
	ScritpArray.push("/js/components/Payment/MenageFolio.js");
	ScritpArray.push("/js/components/Payment/SinglePaymentGroup.js");
	ScritpArray.push("/js/components/Payment/Payment.js");
	CheckAllScript(ScritpArray,function(){CallEditReseredPage(Type,resId);},null);
}
function OpenPaymentForPaymentComponent(resId,Type){
	if($("div[forload=editreserved] #payment-dialog").size() == 0){
		waitingDialog({});
		var div = $("<div>");
		$("div[forload=editreserved]").append(div);
		document.ForPaymentComponentRes = resId;
		document.ForPaymentComponentType = Type;
		div.load("/components/Payment/Payment.jsp",function(){
			var resId = document.ForPaymentComponentRes;
			var Type = document.ForPaymentComponentType;
			delete document.ForPaymentComponentRes;
			delete document.ForPaymentComponentType;
			OpenPaymentPageforRightByResId(resId,Type);
		});
	}else
		OpenPaymentPageforRightByResId(resId,Type);
}